﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;

using DevExpress.XtraGrid.Views.Grid;
using DevTeam;

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class Liste1 : XForm
    {
        int GirisTipiId;
        public Liste1(int _GirisTipiId)
        {
            InitializeComponent();
            GirisTipiId = _GirisTipiId;

            this.Text = "Liste-" + (GirisTipiId == 21 ? "Tela" : "Kumaş");
        }

        BindingSource bsGP, bsGPLines, bsRoll;
        private void StokGiris_List_Load(object sender, EventArgs e)
        {
            //TAM.GelisPartisiLinesTableAdapter = new Datasets.MyDataTableAdapters.GelisPartisiLinesTableAdapter();
            TAM.RollTableAdapter = new Datasets.MyDataTableAdapters.RollTableAdapter();

            //RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();
            //ri.DataSource = new DataView(ExecDatatable("GetVendors"));
            //ri.DisplayMember ="Name";
            //ri.ValueMember = "VendorId";
            //ri.NullText = string.Empty;

            //gvGPLines.Columns["VendorId"].ColumnEdit = ri;

            /*
            ds.GelisPartisiLines.Columns.Add("TopAdedi", typeof(int), "Count(Child(FK_Roll_GelisPartisiLines_GelisPartisiLinesId).RollId)");
            ds.GelisPartisiLines.Columns.Add("Qty2", typeof(decimal), "Sum(Child(FK_Roll_GelisPartisiLines_GelisPartisiLinesId).Qty)");
            ds.GelisPartisiLines.Columns.Add("Fark", typeof(int), "Qty2 - Sum(Child(FK_Roll_GelisPartisiLines_GelisPartisiLinesId).Qty)");
            
            ds.GelisPartisi.Columns.Add("ToplamTopAdedi", typeof(int)).Expression = "Sum(Child(FK_GelisPartisiLines_GelisPartisi_GelisPartisiId).TopAdedi)";
            ds.GelisPartisi.Columns.Add("ToplamMt", typeof(decimal)).Expression = "Sum(Child(FK_GelisPartisiLines_GelisPartisi_GelisPartisiId).Qty2)";
            ds.GelisPartisi.Columns.Add("ToplamFark", typeof(int)).Expression = "Sum(Child(FK_GelisPartisiLines_GelisPartisi_GelisPartisiId).Fark)";
            ds.GelisPartisi.Columns.Add("Hit", typeof(string), string.Empty);

            
            bsGP = new BindingSource(ds, "GelisPartisi");
            bsGPLines = new BindingSource(bsGP, "FK_GelisPartisiLines_GelisPartisi_GelisPartisiId");
            bsRoll = new BindingSource(bsGPLines, "FK_Roll_GelisPartisiLines_GelisPartisiLinesId");

            InitGridView(gvGP, bsGP);
            InitGridView(gvGPLines, bsGPLines);
            InitGridView(gvRoll, bsRoll);
            */
            de.DateTime = DateTime.Now.AddMonths(-1);

            de.ToolTip = "Başlangıç Tarihi";
            de2.ToolTip = "Bitiş Tarihi";

            bsGP = gvGP.Init("GetGP2", GirisTipiId, cmbTip.SelectedIndex, te.Text,
                de.DateTime == new DateTime(1, 1, 1) ? new DateTime(2001, 1, 1) : de.DateTime,
                de2.DateTime == new DateTime(1, 1, 1) ? new DateTime(2071, 1, 1) : de2.DateTime,
                intParse(gleVendor.EditValue), intParse(sleArt.EditValue), intParse(gleTela.EditValue));
            bsGPLines = gvGP.AddDetailGrid(gvGPLines, "GelisPartisiId");
            bsRoll = gvGPLines.AddDetailGrid(gvRoll, "GelisPartisiLinesId");

            gvGPLines.AddColumn("TopAdedi", typeof(int), "COUNT(Child({FK}).RollId)");
            gvGPLines.AddColumn("Qty2", typeof(decimal), "SUM(Child({FK}).Qty)");
            gvGPLines.AddColumn("Fark", typeof(int), "Qty2 - SUM(Child({FK}).Qty)");

            gvGP.AddColumn("ToplamTopAdedi", typeof(int), "SUM(Child({FK}).TopAdedi)");
            gvGP.AddColumn("ToplamMt", typeof(decimal), "SUM(Child({FK}).Qty2)");
            gvGP.AddColumn("ToplamFark", typeof(int), "SUM(Child({FK}).Fark)");



            gvGP.OptionsBehavior.Editable = false;
            gvGPLines.OptionsBehavior.Editable = true;
            gvGPLines.OptionsView.NewItemRowPosition = gvRoll.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;

            gvRoll.ShowingEditor += new System.ComponentModel.CancelEventHandler(gvRoll_ShowingEditor);
            gvRoll.Columns["OwnerId"].Caption = "Mal Sahibi";
            gvGPLines.Columns["VendorId"].Caption = "Üretici";
            gvGPLines.Columns["Qty2"].Caption = "Qty";

            foreach (string str in "GelisPartisiId;Qty".Split(';'))
                gvGPLines.Columns[str].Visible = false;

            int ind = 0;    //Alinin istediği sıra..
            foreach (string str in "RollId;Qty;LotNr;En;Kalite2;KaliteKontrolId;ShelfId;RFIDset;OwnerId".Split(';'))
                gvRoll.Columns[str].VisibleIndex = ind++;

            int gplInd = 0;
            foreach (string str in "GelisPartisiLinesId;Scan;KumasId;TelaId;Qty2;VendorId;UreticiKodu;TopAdedi;Notes;Fark".Split(';'))
                gvGPLines.Columns[str].VisibleIndex = gplInd++;

            gvRoll.Columns["KaliteKontrolId"].VisibleIndex = (ytk(178)) ? gvRoll.Columns["Kalite2"].VisibleIndex + 1 : -1;

            gvGP.AddSummary("ToplamTopAdedi", "ToplamMt", "ToplamFark");
            gvGPLines.AddSummary("Qty2", "TopAdedi", "Fark");
            gvRoll.AddSummary("Qty");

            gvGP.Columns["ToplamMt"].DisplayFormat.FormatType = gvGPLines.Columns["Qty2"].DisplayFormat.FormatType =
                gvRoll.Columns["Qty"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            gvGP.Columns["ToplamMt"].DisplayFormat.FormatString = gvGPLines.Columns["Qty2"].DisplayFormat.FormatString =
                gvRoll.Columns["Qty"].DisplayFormat.FormatString = "#,###.##";

            splitContainerControl1.AutoSize();

            GridManager gm = GridManager.GetManager(gvGP);
            if (ytk(124))
                gm.GridMenu.AddMenu("Bu partideki topların owner'larını topluca değiştir", Degistir);

            //btnKaydet.Click += new EventHandler(btnKaydet_Click);
            //btnYerlestir.Click += new EventHandler(btnYerlestir_Click);
            //gleShelf.Properties.Assign(RI(Rp.Shelf));
            //btnYerlestir.Enabled = false;
            //gleShelf.EditValueChanged += new EventHandler(gleShelf_EditValueChanged);
            //bsGP.CurrentChanged += new EventHandler(bsGP_CurrentChanged);

            btnGo.Click += new EventHandler(btnGo_Click);

            cmbTip.SelectedIndex = -1;
            cmbTip.SelectedIndexChanged += new EventHandler(cmbTip_SelectedIndexChanged);
            cmbTip.SelectedIndex = 0;

            gvGPLines.RowStyle += new RowStyleEventHandler(gvGPLines_RowStyle);
            gvRoll.RowStyle += new RowStyleEventHandler(gvGPLines_RowStyle);

            sleArt.Properties.Assign(RI(Rp.V_Kumas));
            sleArt.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Default;

            //sleArt.EditValueChanged += new EventHandler(sleArt_EditValueChanged);

            gleTela.Properties.Assign(RI(Rp.Tela));
            gleTela.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Default;

            //OA2
            gvGPLines.ShowingEditor += new System.ComponentModel.CancelEventHandler(gvGPLines_ShowingEditor);
            gvGPLines.DoubleClick += new EventHandler(gvGPLines_DoubleClick);

            splitContainerControl2.AutoSize();

            gleGirisTipi.Properties.Assign(RI(Rp.HareketTipi));
            gleGirisTipi.Properties.DataSource = new DataView(AppSession.Lookups.HareketTipi, "Category = 'GİRİŞ'", "Name", DataViewRowState.OriginalRows);
            gleGirisTipi.EditValueChanged += new EventHandler(gleGirisTipi_EditValueChanged);
            gleGirisTipi.EditValue = GirisTipiId;

            te.Location = gleVendor.Location = sleArt.Location = gleTela.Location;
            //de2.Location = new Point(de.Location.X + de.Width + 5, de2.Location.Y);
            gvGPLines.OptionsView.EnableAppearanceOddRow = gvGPLines.OptionsView.EnableAppearanceEvenRow = false;
            gvRoll.OptionsView.EnableAppearanceOddRow = gvRoll.OptionsView.EnableAppearanceEvenRow = false;

            gleVendor.Properties.Assign(RI(Rp.Vendor));
            gleVendor.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Default;

        }

        private void Degistir(object sender, EventArgs e)
        {
            using (TopDuzeltmeGP duzeltme = new TopDuzeltmeGP(intParse(bsGP, "GelisPartisiId")))
            {
                duzeltme.ShowDialog();
            }
        }


        void btnGo_Click(object sender, EventArgs e)
        {
            /*
            if (te.Text != string.Empty)
            {
                ds.xRollGP.Clear();
                GetDetails("xRollGP", "GetRollGP", intParse(te.Text));
                if (ds.xRollGP.Rows.Count > 0)
                {
                    gvGP.FocusedRowHandle = gvGP.LocateByDisplayText(0, gvGP.Columns["GelisPartisiId"], ds.xRollGP[0]["GelisPartisiId"].ToString());
                    gvGPLines.FocusedRowHandle = gvGPLines.LocateByDisplayText(0, gvGPLines.Columns["GelisPartisiLinesId"], ds.xRollGP[0]["GelisPartisiLinesId"].ToString());
                    gvRoll.FocusedRowHandle = gvRoll.LocateByDisplayText(0, gvRoll.Columns["RollId"], ds.xRollGP[0]["RollId"].ToString());
                }
            }
            */

            ds.Clear();
            splitContainerControl1.Enabled = false;
            btnGo.Enabled = false;
            gvGP.RefreshDataSource("GetGP2", GirisTipiId, cmbTip.SelectedIndex, te.Text,
                de.DateTime == new DateTime(1, 1, 1) ? new DateTime(2001, 1, 1) : de.DateTime,
                de2.DateTime == new DateTime(1, 1, 1) ? new DateTime(2071, 1, 1) : de2.DateTime,
                intParse(gleVendor.EditValue), intParse(sleArt.EditValue), intParse(gleTela.EditValue));
            btnGo.Enabled = true;

            gvGP.FormatAsDate("BelgeTarihi");

            //gvGP.FocusedRowHandle = gvGP.LocateByDisplayText(0, gvGP.Columns["GelisPartisiId"], ds.xRollGP[0]["GelisPartisiId"].ToString());
            gvGPLines.FocusedRowHandle = gvGPLines.LocateByDisplayText(0, gvGPLines.Columns["Hit"], "1");
            gvRoll.FocusedRowHandle = gvRoll.LocateByDisplayText(0, gvRoll.Columns["Hit"], "1");

            splitContainerControl1.Enabled = true;
            gvGP.BestFitColumns();
            gvGPLines.BestFitColumns();
            gvRoll.BestFitColumns();
        }

        void cmbTip_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cmbTip.SelectedIndex)
            {
                case 0:
                    te.Visible = true; sleArt.Visible = gleVendor.Visible = gleTela.Visible = false;
                    //lblProc.Text = "GPId: " + te.Text;
                    break;

                case 1:
                    te.Visible = true; sleArt.Visible = gleVendor.Visible = gleTela.Visible = false;
                    //lblProc.Text = "GPLId: " + te.Text;
                    break;

                case 2:
                    sleArt.Visible = true; te.Visible = gleVendor.Visible = gleTela.Visible = false;
                    //lblProc.Text = "Art: " + AppSession.Lookups.V_Kumas.FindByProductId(intParse(bsGPLines, "ProductId")).Name;
                    break;

                case 3:
                    gleTela.Visible = true; te.Visible = gleVendor.Visible = sleArt.Visible = false;
                    //lblProc.Text = "Art: " + AppSession.Lookups.V_Kumas.FindByProductId(intParse(bsGPLines, "ProductId")).Name;
                    break;

                case 4:
                    te.Visible = true; sleArt.Visible = gleVendor.Visible = gleTela.Visible = false;
                    //lblProc.Text = "TopId: " + te.Text;
                    break;

                case 5:
                    gleVendor.Visible = true; te.Visible = sleArt.Visible = gleTela.Visible = false;
                    //lblProc.Text = "Uretici: " + AppSession.Lookups.Vendor.FindByVendorId(intParse(gleVendor.EditValue)).Name;
                    break;

                case 6:
                    te.Visible = true; sleArt.Visible = gleVendor.Visible = gleTela.Visible = false;
                    //lblProc.Text = "UreticiKodu: " + te.Text;
                    break;

                case 7:
                    te.Visible = sleArt.Visible = gleVendor.Visible = gleTela.Visible = false;
                    //lblProc.Text = "TÜMÜ"
                    break;
            }
        }

        void btnKaydet_Click(object sender, EventArgs e)
        {
            Save();
        }

        void gleGirisTipi_EditValueChanged(object sender, EventArgs e)
        {
            ds.Clear();
            txtInfo.Caption = string.Empty;
            GirisTipiId = intParse(gleGirisTipi.EditValue);

            if (GirisTipiId == 21)
                gvGPLines.ShowProductIdAsTela();
            else
                gvGPLines.ShowProductIdAsKumas();

            //gvGPLines.Columns["OrderRef"].Width = 80;
        }

        //void Sifirla_Click(object sender, EventArgs e)
        //{
        //    if (XtraMessageBox.Show("Emin misiniz?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
        //    {
        //        GetDetails("Roll", "UpdTopSifirla", intParse(bsGP, "GelisPartisiId"));
        //    }
        //}

        //void gvGPLines_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        //{
        //    e.Cancel = !(((GridView)sender).FocusedColumn.FieldName != "ProductId" || WhoAmI == 17);
        //        //intParse(((GridView)sender).GetFocusedRowCellValue("GelisPartisiLinesId")) > 0;
        //}

        void gvGPLines_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = gvGPLines.FocusedColumn.FieldName.StartsWith("Uretici") ||
                gvGPLines.FocusedColumn.FieldName.StartsWith("Vendor");
        }

        void gvGPLines_DoubleClick(object sender, EventArgs e)
        {
            if (gvGPLines.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
                if (gvGPLines.FocusedColumn.FieldName.StartsWith("Uretici") ||
                gvGPLines.FocusedColumn.FieldName.StartsWith("Vendor"))
                    if (intParse(bsGPLines, "ProductId") > 0)
                        using (Kodlar kodlar = new Kodlar(intParse(bsGPLines, "ProductId"), true))
                            if (kodlar.ShowDialog() == DialogResult.OK)
                            {
                                gvGPLines.SetFocusedRowCellValue("VendorId", kodlar.VendorId);
                                gvGPLines.SetFocusedRowCellValue("UreticiKodu", kodlar.UreticiKodu);
                            }
        }


        //void sleArt_EditValueChanged(object sender, EventArgs e)
        //{
        //    if (sleArt.EditValue != null)
        //    {
        //        int ProductId = intParse(sleArt.EditValue);
        //        bsGPLines.Filter = "ProductId = " + ProductId.ToString();
        //        foreach (DataRow dr in ds.GelisPartisi.Rows)
        //            dr["Hit"] = string.Empty;

        //        foreach (DataRow dr in ds.GelisPartisiLines.Rows)
        //            if (intParse(dr["ProductId"]) == ProductId)
        //                ds.GelisPartisi.FindByGelisPartisiId(intParse(dr["GelisPartisiId"]))["Hit"] = "*";

        //        bsGP.Filter = "Hit = '*'";
        //        gvGPLines.RefreshData();
        //        gvGP.RefreshData();
        //    }
        //}

        //void btnFiltreSil_Click(object sender, EventArgs e)
        //{
        //    sleArt.EditValue = null;
        //    bsGPLines.Filter = bsGP.Filter = string.Empty;
        //    gvGPLines.RefreshData();
        //    gvGP.RefreshData();
        //}        

        void gvGPLines_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
                if ((sender as GridView).GetRowCellValue(e.RowHandle, "Hit") != null)
                    if (intParse((sender as GridView).GetRowCellValue(e.RowHandle, "Hit")) == 1)
                        e.Appearance.BackColor = e.Appearance.BackColor2 = Color.LightSkyBlue;
        }

        //void StokGirisler_DoubleClick(object sender, EventArgs e)
        //{
        //    using (FuzzySearch fuzzy = new FuzzySearch())
        //    {
        //        if (fuzzy.ShowDialog() == DialogResult.OK)
        //        {
        //            (sender as GridLookUpEdit).EditValue = fuzzy.ProductId;
        //            //gvGPLines.SetFocusedValue(fuzzy.ProductId);
        //        }

        //    }
        //}

        //void bsGP_CurrentChanged(object sender, EventArgs e)
        //{
        //    lblProc.Text = "GPId: " + intParse(bsGP, "GelisPartisiId");
        //    gvGPLines.BestFitColumns();
        //    //gvGPLines.Columns["OrderRef"].Width = 80;

        //}

        //void gleShelf_EditValueChanged(object sender, EventArgs e)
        //{
        //    btnYerlestir.Enabled = gleShelf.EditValue != DBNull.Value;
        //}

        //void btnYerlestir_Click(object sender, EventArgs e)
        //{
        //    GetDetails("GelisPartisi;GelisPartisiLines;Roll", "UpdGP", intParse(bsGP, "GelisPartisiId"), intParse(gleShelf.EditValue));
        //    ShowInfoMessage("Güncellendi! Bu partideki topların tamamını belirttiğiniz rafa yerleştirmeyi unutmayın.");
        //}

        void gvRoll_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //OA3
            e.Cancel = !";Qty;LotNr;En;Kalite2;ShelfId;OwnerId;VendorId;Note;KaliteKontrolId;".Contains(";" + ((GridView)sender).FocusedColumn.FieldName + ";");
        }

    }
}
